<?php

/**
 * Maikuro Framework
 *
 * LICENSE:
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * The license is bundled with this package in the file LICENSE.txt.
 * You may also obtain a copy of the License at this URL:
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @copyright  Copyright (c) 2010, Jonathan Hedrén
 * @author     Jonathan Hedrén <jonathan.hedren@gmail.com>
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 */

/**
 * @see IMailHandler
 */
require_once 'IMailHandler.php';

/**
 * The StandardMailHandler class uses the mail() function.
 */
class StandardMailHandler implements IMailHandler
{
    /**
     * The From address.
     *
     * @var string
     */
    protected $from;

    /**
     * Constructor.
     *
     * @param string $from
     * @return StandardMailHandler
     */
    public function  __construct($from = null /*, TODO: $fromName = null */)
    {
        // TODO: Filter::email($from)
        $this->from = $from;
        return $this;
    }

    /**
     * Sends the mail.
     *
     * @param Mail $mail
     * @return StandardMailHandler
     */
    public function sendMail(Mail $mail)
    {
        if ($mail->getFrom() !== null) {
            $from = $mail->getFrom();
        } else if ($this->from !== null) {
            // TODO: fromName: if (is_array($this->from)) {
            $from = Mail::FROM . ': ' . $this->from . "\r\n";
        } else {
            throw new Exception('A "from" email address is required.');
        }
        
        $omittedHeaders = array(Mail::FROM, Mail::TO, Mail::SUBJECT);
        $headers = $from . $mail->getHeaders(true, $omittedHeaders);
        
        $result = mail(
            $mail->getTo(),
            $mail->getSubject(false),
            $mail->getBody(),
            $headers
        );
        if (!$result) {
            throw new Exception('Could not send mail.');
        }
        return $this;
    }
}
